package com.begamer.card.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;

import com.begamer.card.common.Constant;
import com.begamer.card.model.dao.ManagerLoginDao;
import com.begamer.card.model.dao.ModelDao;
import com.begamer.card.model.dao.PrivilegeDao;
import com.begamer.card.model.pojo.Manager;
import com.begamer.card.model.pojo.Model;
import com.begamer.card.model.pojo.Privilege;

public class PrivilegeController extends AbstractMultiActionController {
	
	@Autowired
	private PrivilegeDao privilegeDao;
	@Autowired
	private ManagerLoginDao managerLoginDao;
	@Autowired
	private ModelDao modelDao;
	
	private static Logger logger = Logger.getLogger(PrivilegeController.class);
	
	public ModelAndView addGo(HttpServletRequest request, HttpServletResponse response)
	{
		List<Manager> list = managerLoginDao.getManagers();
		request.setAttribute("list", list);
		return new ModelAndView("/gm/addPrivilege.vm");
	}
	
	/***************************************************************************
	 * 添加权限
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView addPrivilege(HttpServletRequest request, HttpServletResponse response)
	{
		// 选择的模块
		String[] model = request.getParameterValues("model");
		int managerId = Integer.parseInt(request.getParameter("managerId"));
		// 查询该GM所拥有的模块
		List<Privilege> list = privilegeDao.getPrivilegeByManagerId(managerId);
		if (model == null)
		{// 一个都不选
			for (int i = 0; i < list.size(); i++)
			{
				Privilege privilege = list.get(i);
				privilegeDao.delete(privilege);
			}
		}
		else
		{
			// 判断是否需要添加
			for (int i = 0; i < model.length; i++)
			{
				int num = Integer.parseInt(model[i]);
				Model model2 = modelDao.oneModel(num);
				// System.out.println("num到底是什么"+num);
				int count = 0;// 标识操作动作（0没有该功能，1有该功能）
				for (int j = 0; j < list.size(); j++)
				{
					Privilege privilege = list.get(j);
					if (model2.getM_id() == privilege.getAccessValue())
					{// 已有的
						count = 1;
						break;
					}
				}
				if (count == 0)// 新添加的
				{
					Manager manager = managerLoginDao.getOneById(managerId);
					Privilege privilege = new Privilege();
					privilege.setMaster(manager.getName());
					privilege.setMasterValue(managerId);
					privilege.setAccess(model2.getName());
					privilege.setAccessValue(model2.getM_id());
					privilege.setOperation(1);
					privilegeDao.save(privilege);
				}
			}
			// 判断是否需要删除
			for (int i = 0; i < list.size(); i++)
			{
				Privilege privilege = list.get(i);
				int count = 0;// 标识操作动作（0需要删除，1不需要删除）
				int num = 0;// 功能模块编号
				for (int j = 0; j < model.length; j++)
				{
					num = Integer.parseInt(model[j]);
					Model model2 = modelDao.oneModel(num);
					if (privilege.getAccessValue() == model2.getM_id())
					{
						count = 1;
						break;
					}
				}
				if (count == 0)
				{
					privilegeDao.delete(privilege);
				}
			}
		}
		// 重新设置gm权限
		List<Privilege> list2 = privilegeDao.getPrivilegeByManagerId(managerId);
		request.getSession().removeAttribute(Constant.GM_PRIVILEGE);
		request.getSession().setAttribute(Constant.GM_PRIVILEGE, list2);
		allPrivilege(request, response);
		return new ModelAndView("/gm/allPrivilege.vm");
	}
	
	public ModelAndView allPrivilege(HttpServletRequest request, HttpServletResponse response)
	{
		boolean is = checkQx(getManager(request).getId());
		if (!is)
		{
			return new ModelAndView("gm/noqx.vm");
		}
		List<Privilege> list = privilegeDao.find();
		request.setAttribute("privileges", list);
		return new ModelAndView("/gm/allPrivilege.vm");
	}
	
	/***************************************************************************
	 * 根据区服查询GM
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView getManagerByServerId(HttpServletRequest request, HttpServletResponse response)
	{
		logger.info("sessionid:" + request.getSession().getId());
		int serverId = Integer.parseInt(request.getParameter("serverId"));
		List<Manager> list = managerLoginDao.getManagerByServerId(serverId);
		response.setCharacterEncoding("UTF-8");
		StringBuilder sBuilder = new StringBuilder();
		try
		{
			if (list.size() > 0)
			{
				for (int i = 0; i < list.size(); i++)
				{
					Manager manager = list.get(i);
					sBuilder.append("<option name=\"managerId\" value='" + manager.getId() + "'>" + manager.getName() + "</option>");
				}
			}
			response.getWriter().write(sBuilder.toString());
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}
	
	public ModelAndView getManagerPrivilege(HttpServletRequest request, HttpServletResponse response)
	{
		logger.info(request.getSession().getId());
		int managerId = Integer.parseInt(request.getParameter("managerId"));
		// Manager manager = (Manager)
		// request.getSession().getAttribute(Constant.LOGIN_USER);
		// System.out.println("manager:" + managerId);
		// 获得所有的功能模块
		List<Model> modelList = modelDao.findAllModel();
		// 获得该GM拥有的权限功能
		List<Privilege> list = privilegeDao.getPrivilegeByManagerId(managerId);
		response.setCharacterEncoding("UTF-8");
		StringBuilder sBuilder = new StringBuilder();
		try
		{
			if (modelList.size() > 0)
			{
				for (int i = 0; i < modelList.size(); i++)
				{
					Model model = modelList.get(i);
					sBuilder.append("&nbsp;&nbsp;&nbsp;&nbsp;<input type=\"checkbox\" name=\"model\" value='" + model.getId() + "'");
					for (int j = 0; j < list.size(); j++)
					{
						Privilege privilege = list.get(j);
						if (model.getM_id() == privilege.getAccessValue())
						{
							sBuilder.append("checked");
							break;
						}
					}
					sBuilder.append("/>" + model.getName());
					if ((i + 1) % 4 == 0)
					{
						sBuilder.append("</br>");
					}
				}
			}
			response.getWriter().write(sBuilder.toString());
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}
}
